#region

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Data.SQLite;
using System.Data;
using System.Text;


#endregion

namespace Test
{
    /// <summary>
    /// The SQLiteHelper class is intended to encapsulate high performance, scalable best practices for 
    /// common uses of SqlClient
    /// </summary>
    public partial class SqliteHelper
    {
        #region private utility methods & constructors

        public static readonly string ConnectionString = string.Format(@"Data Source={0}\WrappingMachine.sqlite;Pooling=true;FailIfMissing=false", System.AppDomain.CurrentDomain.BaseDirectory);
        //private static readonly string ConnectionString = @"Data Source=E:\PowerWeight.sqlite";

        public static SQLiteConnection NewConnection
        {
            get
            {
                return new SQLiteConnection(ConnectionString);
            }
        }

        // Since this class provides only static methods, make the default constructor private to prevent 
        // instances from being created with "new SQLiteHelper()"
        private SqliteHelper()
        {
        }

        /// <summary>
        /// This method is used to attach array of SQLiteParameters to a SQLiteCommand.
        /// 
        /// This method will assign a value of DbNull to any parameter with a direction of
        /// InputOutput and a value of null.  
        /// 
        /// This behavior will prevent default values from being used, but
        /// this will be the less common case than an intended pure output parameter (derived as InputOutput)
        /// where the user provided no input value.
        /// </summary>
        /// <param name="command">The command to which the parameters will be added</param>
        /// <param name="commandParameters">An array of SQLiteParameters to be added to command</param>
        private static void AttachParameters(SQLiteCommand command, IEnumerable<SQLiteParameter> commandParameters)
        {
            if (command == null) throw new ArgumentNullException("command");
            if (commandParameters != null)
            {
                foreach (SQLiteParameter p in commandParameters)
                {
                    if (p != null)
                    {
                        // Check for derived output value with no value assigned
                        if ((p.Direction == ParameterDirection.InputOutput ||
                             p.Direction == ParameterDirection.Input) &&
                            (p.Value == null))
                        {
                            p.Value = DBNull.Value;
                        }
                        command.Parameters.Add(p);
                    }
                }
            }
        }

        /// <summary>
        /// This method opens (if necessary) and assigns a connection, transaction, command type and parameters 
        /// to the provided command
        /// </summary>
        /// <param name="command">The SQLiteCommand to be prepared</param>
        /// <param name="connection">A valid SQLiteConnection, on which to execute this command</param>
        /// <param name="transaction">A valid SQLiteTransaction, or 'null'</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SQLiteParameters to be associated with the command or 'null' if no parameters are required</param>
        /// <param name="mustCloseConnection"><c>true</c> if the connection was opened by the method, otherwose is false.</param>
        private static void PrepareCommand(SQLiteCommand command, SQLiteConnection connection, SQLiteTransaction transaction, string commandText, IEnumerable<SQLiteParameter> commandParameters, out bool mustCloseConnection)
        {
            if (command == null) throw new ArgumentNullException("command");
            if (string.IsNullOrEmpty(commandText)) throw new ArgumentNullException("commandText");

            // If the provided connection is not open, we will open it
            if (connection.State != ConnectionState.Open)
            {
                mustCloseConnection = true;
                connection.Open();
            }
            else
            {
                mustCloseConnection = false;
            }

            // Associate the connection with the command
            command.Connection = connection;

            // Set the command text (stored procedure name or SQL statement)
            command.CommandText = commandText;

            // If we were provided a transaction, assign it
            if (transaction != null)
            {
                if (transaction.Connection == null)
                    throw new ArgumentException(
                        "The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
                command.Transaction = transaction;
            }

            // Attach the command parameters if they are provided
            if (commandParameters != null)
            {
                AttachParameters(command, commandParameters);
            }
            return;
        }

        #endregion private utility methods & constructors

        #region ExecuteNonQuery

        /// <summary>
        /// Execute a SQLiteCommand (that returns no resultset and takes no parameters) against the database specified in 
        /// the connection string
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery("PublishOrders");
        /// </remarks>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>An int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteNonQuery(ConnectionString, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns no resultset) against the database specified in the connection string 
        /// using the provided parameters
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery("PublishOrders", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>An int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(string commandText, params SQLiteParameter[] commandParameters)
        {
            return ExecuteNonQuery(ConnectionString, commandText, commandParameters);
        }


        /// <summary>
        /// Execute a SQLiteCommand (that returns no resultset and takes no parameters) against the database specified in 
        /// the connection string
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, "PublishOrders");
        /// </remarks>
        /// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>An int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(string connectionString, string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteNonQuery(connectionString, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns no resultset) against the database specified in the connection string 
        /// using the provided parameters
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, "PublishOrders", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>An int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(string connectionString, string commandText, params SQLiteParameter[] commandParameters)
        {
            if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException("connectionString");

            // Create & open a SQLiteConnection, and dispose of it after we are done
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                // Call the overload that takes a connection in place of the connection string
                return ExecuteNonQuery(connection, commandText, commandParameters);
            }
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns no resultset and takes no parameters) against the provided SQLiteConnection. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(conn, "PublishOrders");
        /// </remarks>
        /// <param name="connection">A valid SQLiteConnection</param>
        /// <returns>An int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SQLiteConnection connection, string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteNonQuery(connection, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns no resultset) against the specified SQLiteConnection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(conn, "PublishOrders", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">A valid SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>An int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SQLiteConnection connection, string commandText, params SQLiteParameter[] commandParameters)
        {
            if (connection == null) throw new ArgumentNullException("connection");
            if (connection.State != ConnectionState.Closed) connection.Close();
            connection.Open();

            // Create a command and prepare it for execution
            SQLiteCommand cmd = new SQLiteCommand();
            bool mustCloseConnection = false;
            PrepareCommand(cmd, connection, null, commandText, commandParameters, out mustCloseConnection);
            // Finally, execute the command
            int retval = cmd.ExecuteNonQuery();

            // Detach the SQLiteParameters from the command object, so they can be used again
            cmd.Parameters.Clear();
            if (mustCloseConnection)
                connection.Close();
            return retval;
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns no resultset and takes no parameters) against the provided SQLiteTransaction. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(trans, "PublishOrders");
        /// </remarks>
        /// <param name="transaction">A valid SQLiteTransaction</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>An int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SQLiteTransaction transaction, string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteNonQuery(transaction, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns no resultset) against the specified SQLiteTransaction
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(trans, "GetOrders", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="transaction">A valid SQLiteTransaction</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>An int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SQLiteTransaction transaction, string commandText, params SQLiteParameter[] commandParameters)
        {
            if (transaction == null) throw new ArgumentNullException("transaction");
            if (transaction != null && transaction.Connection == null)
                throw new ArgumentException(
                    "The transaction was rollbacked or commited, please provide an open transaction.", "transaction");

            // Create a command and prepare it for execution
            SQLiteCommand cmd = new SQLiteCommand();
            bool mustCloseConnection = false;
            PrepareCommand(cmd, transaction.Connection, transaction, commandText, commandParameters,
                           out mustCloseConnection);

            // Finally, execute the command
            int retval = cmd.ExecuteNonQuery();

            // Detach the SQLiteParameters from the command object, so they can be used again
            cmd.Parameters.Clear();
            return retval;
        }

        #endregion ExecuteNonQuery

        #region ExecuteDataset

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset and takes no parameters) against the database specified in 
        /// the connection string. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset("GetOrders");
        /// </remarks>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>A dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteDataset(ConnectionString, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset("GetOrders", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>A dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(string commandText, params SQLiteParameter[] commandParameters)
        {
            // Call the overload that takes a connection in place of the connection string
            return ExecuteDataset(ConnectionString, commandText, commandParameters);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset and takes no parameters) against the database specified in 
        /// the connection string. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset(connString, "GetOrders");
        /// </remarks>
        /// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>A dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(string connectionString, string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteDataset(connectionString, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset(connString, "GetOrders", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>A dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(string connectionString, string commandText, params SQLiteParameter[] commandParameters)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString");

            // Create & open a SQLiteConnection, and dispose of it after we are done
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                // Call the overload that takes a connection in place of the connection string
                return ExecuteDataset(connection, commandText, commandParameters);
            }
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset and takes no parameters) against the provided SQLiteConnection. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset(conn, "GetOrders");
        /// </remarks>
        /// <param name="connection">A valid SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>A dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(SQLiteConnection connection, string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteDataset(connection, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset) against the specified SQLiteConnection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset(conn, "GetOrders", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">A valid SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>A dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(SQLiteConnection connection, string commandText, params SQLiteParameter[] commandParameters)
        {
            if (connection == null) throw new ArgumentNullException("connection");

            // Create a command and prepare it for execution
            SQLiteCommand cmd = new SQLiteCommand();
            bool mustCloseConnection = false;
            PrepareCommand(cmd, connection, null, commandText, commandParameters, out mustCloseConnection);

            // Create the DataAdapter & DataSet
            using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd))
            {
                DataSet ds = new DataSet();

                // Fill the DataSet using default values for DataTable names, etc
                da.Fill(ds);

                // Detach the SQLiteParameters from the command object, so they can be used again
                cmd.Parameters.Clear();

                if (mustCloseConnection)
                    connection.Close();

                // Return the dataset
                return ds;
            }
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset and takes no parameters) against the provided SQLiteTransaction. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset(trans, "GetOrders");
        /// </remarks>
        /// <param name="transaction">A valid SQLiteTransaction</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>A dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(SQLiteTransaction transaction, string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteDataset(transaction, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset) against the specified SQLiteTransaction
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset(trans, "GetOrders", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="transaction">A valid SQLiteTransaction</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>A dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(SQLiteTransaction transaction, string commandText, params SQLiteParameter[] commandParameters)
        {
            if (transaction == null) throw new ArgumentNullException("transaction");
            if (transaction != null && transaction.Connection == null)
                throw new ArgumentException(
                    "The transaction was rollbacked or commited, please provide an open transaction.", "transaction");

            // Create a command and prepare it for execution
            SQLiteCommand cmd = new SQLiteCommand();
            bool mustCloseConnection = false;
            PrepareCommand(cmd, transaction.Connection, transaction, commandText, commandParameters,
                           out mustCloseConnection);

            // Create the DataAdapter & DataSet
            using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd))
            {
                DataSet ds = new DataSet();

                // Fill the DataSet using default values for DataTable names, etc
                da.Fill(ds);

                // Detach the SQLiteParameters from the command object, so they can be used again
                cmd.Parameters.Clear();

                // Return the dataset
                return ds;
            }
        }

        #endregion ExecuteDataset

        #region ExecuteReader

        /// <summary>
        /// This enum is used to indicate whether the connection was provided by the caller, or created by SQLiteHelper, so that
        /// we can set the appropriate CommandBehavior when calling ExecuteReader()
        /// </summary>
        private enum SQLiteConnectionOwnership
        {
            /// <summary>Connection is owned and managed by SQLiteHelper</summary>
            Internal,
            /// <summary>Connection is owned and managed by the caller</summary>
            External
        }

        /// <summary>
        /// Create and prepare a SQLiteCommand, and call ExecuteReader with the appropriate CommandBehavior.
        /// </summary>
        /// <remarks>
        /// If we created and opened the connection, we want the connection to be closed when the DataReader is closed.
        /// 
        /// If the caller provided the connection, we want to leave it to them to manage.
        /// </remarks>
        /// <param name="connection">A valid SQLiteConnection, on which to execute this command</param>
        /// <param name="transaction">A valid SQLiteTransaction, or 'null'</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SQLiteParameters to be associated with the command or 'null' if no parameters are required</param>
        /// <param name="connectionOwnership">Indicates whether the connection parameter was provided by the caller, or created by SQLiteHelper</param>
        /// <returns>SQLiteDataReader containing the results of the command</returns>
        private static SQLiteDataReader ExecuteReader(SQLiteConnection connection, SQLiteTransaction transaction, string commandText, IEnumerable<SQLiteParameter> commandParameters, SQLiteConnectionOwnership connectionOwnership)
        {
            if (connection == null) throw new ArgumentNullException("connection");

            bool mustCloseConnection = false;
            // Create a command and prepare it for execution
            SQLiteCommand cmd = new SQLiteCommand();
            try
            {
                PrepareCommand(cmd, connection, transaction, commandText, commandParameters,
                               out mustCloseConnection);

                // Create a reader
                SQLiteDataReader dataReader;

                // Call ExecuteReader with the appropriate CommandBehavior
                if (connectionOwnership == SQLiteConnectionOwnership.External)
                {
                    dataReader = cmd.ExecuteReader();
                }
                else
                {
                    dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                }

                // Detach the SQLiteParameters from the command object, so they can be used again.
                // HACK: There is a problem here, the output parameter values are fletched 
                // when the reader is closed, so if the parameters are detached from the command
                // then the SqlReader can�?set its values. 
                // When this happen, the parameters can�?be used again in other command.
                bool canClear = true;
                foreach (SQLiteParameter commandParameter in cmd.Parameters)
                {
                    if (commandParameter.Direction != ParameterDirection.Input)
                        canClear = false;
                }

                if (canClear)
                {
                    cmd.Parameters.Clear();
                }

                return dataReader;
            }
            catch
            {
                if (mustCloseConnection)
                    connection.Close();
                throw;
            }
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset and takes no parameters) against the database specified in 
        /// the connection string. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SQLiteDataReader dr = ExecuteReader("GetOrders");
        /// </remarks>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>A SQLiteDataReader containing the resultset generated by the command</returns>
        public static SQLiteDataReader ExecuteReader(string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteReader(ConnectionString, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SQLiteDataReader dr = ExecuteReader("GetOrders", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>A SQLiteDataReader containing the resultset generated by the command</returns>
        public static SQLiteDataReader ExecuteReader(string commandText, params SQLiteParameter[] commandParameters)
        {
            return ExecuteReader(ConnectionString, commandText, commandParameters);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset and takes no parameters) against the database specified in 
        /// the connection string. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SQLiteDataReader dr = ExecuteReader(connString, "GetOrders");
        /// </remarks>
        /// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>A SQLiteDataReader containing the resultset generated by the command</returns>
        public static SQLiteDataReader ExecuteReader(string connectionString, string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteReader(connectionString, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SQLiteDataReader dr = ExecuteReader(connString, "GetOrders", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>A SQLiteDataReader containing the resultset generated by the command</returns>
        public static SQLiteDataReader ExecuteReader(string connectionString, string commandText, params SQLiteParameter[] commandParameters)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString");
            SQLiteConnection connection = null;
            try
            {
                connection = new SQLiteConnection(connectionString);
                connection.Open();

                // Call the private overload that takes an internally owned connection in place of the connection string
                return ExecuteReader(connection, null, commandText, commandParameters,
                                     SQLiteConnectionOwnership.Internal);
            }
            catch
            {
                // If we fail to return the SqlDatReader, we need to close the connection ourselves
                if (connection != null) connection.Close();
                throw;
            }
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset and takes no parameters) against the provided SQLiteConnection. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SQLiteDataReader dr = ExecuteReader(conn, "GetOrders");
        /// </remarks>
        /// <param name="connection">A valid SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>A SQLiteDataReader containing the resultset generated by the command</returns>
        public static SQLiteDataReader ExecuteReader(SQLiteConnection connection, string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteReader(connection, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset) against the specified SQLiteConnection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SQLiteDataReader dr = ExecuteReader(conn, "GetOrders", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">A valid SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>A SQLiteDataReader containing the resultset generated by the command</returns>
        public static SQLiteDataReader ExecuteReader(SQLiteConnection connection, string commandText, params SQLiteParameter[] commandParameters)
        {
            // Pass through the call to the private overload using a null transaction value and an externally owned connection
            return ExecuteReader(connection, null, commandText, commandParameters,
                                 SQLiteConnectionOwnership.External);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset and takes no parameters) against the provided SQLiteTransaction. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SQLiteDataReader dr = ExecuteReader(trans, "GetOrders");
        /// </remarks>
        /// <param name="transaction">A valid SQLiteTransaction</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>A SQLiteDataReader containing the resultset generated by the command</returns>
        public static SQLiteDataReader ExecuteReader(SQLiteTransaction transaction, string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteReader(transaction, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset) against the specified SQLiteTransaction
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///   SQLiteDataReader dr = ExecuteReader(trans, "GetOrders", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="transaction">A valid SQLiteTransaction</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>A SQLiteDataReader containing the resultset generated by the command</returns>
        public static SQLiteDataReader ExecuteReader(SQLiteTransaction transaction, string commandText, params SQLiteParameter[] commandParameters)
        {
            if (transaction == null) throw new ArgumentNullException("transaction");
            if (transaction != null && transaction.Connection == null)
                throw new ArgumentException(
                    "The transaction was rollbacked or commited, please provide an open transaction.", "transaction");

            // Pass through to private overload, indicating that the connection is owned by the caller
            return ExecuteReader(transaction.Connection, transaction, commandText, commandParameters,
                                 SQLiteConnectionOwnership.External);
        }

        #endregion ExecuteReader

        #region ExecuteScalar

        /// <summary>
        /// Execute a SQLiteCommand (that returns a 1x1 resultset and takes no parameters) against the database specified in 
        /// the connection string. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int orderCount = (int)ExecuteScalar("GetOrderCount");
        /// </remarks>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
        public static object ExecuteScalar(string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteScalar(ConnectionString, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a 1x1 resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int orderCount = (int)ExecuteScalar("GetOrderCount", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
        public static object ExecuteScalar(string commandText, params SQLiteParameter[] commandParameters)
        {
            // Call the overload that takes a connection in place of the connection string
            return ExecuteScalar(ConnectionString, commandText, commandParameters);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a 1x1 resultset and takes no parameters) against the database specified in 
        /// the connection string. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int orderCount = (int)ExecuteScalar(connString, "GetOrderCount");
        /// </remarks>
        /// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
        public static object ExecuteScalar(string connectionString, string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteScalar(connectionString, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a 1x1 resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int orderCount = (int)ExecuteScalar(connString, "GetOrderCount", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
        public static object ExecuteScalar(string connectionString, string commandText,
                                           params SQLiteParameter[] commandParameters)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString");
            // Create & open a SQLiteConnection, and dispose of it after we are done
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                // Call the overload that takes a connection in place of the connection string
                return ExecuteScalar(connection, commandText, commandParameters);
            }
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a 1x1 resultset and takes no parameters) against the provided SQLiteConnection. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int orderCount = (int)ExecuteScalar(conn, "GetOrderCount");
        /// </remarks>
        /// <param name="connection">A valid SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
        public static object ExecuteScalar(SQLiteConnection connection, string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteScalar(connection, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a 1x1 resultset) against the specified SQLiteConnection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int orderCount = (int)ExecuteScalar(conn, "GetOrderCount", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">A valid SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
        public static object ExecuteScalar(SQLiteConnection connection, string commandText,
                                           params SQLiteParameter[] commandParameters)
        {
            if (connection == null) throw new ArgumentNullException("connection");

            // Create a command and prepare it for execution
            SQLiteCommand cmd = new SQLiteCommand();

            bool mustCloseConnection = false;
            PrepareCommand(cmd, connection, null, commandText, commandParameters, out mustCloseConnection);

            // Execute the command & return the results
            object retval = cmd.ExecuteScalar();

            // Detach the SQLiteParameters from the command object, so they can be used again
            cmd.Parameters.Clear();

            if (mustCloseConnection)
                connection.Close();

            return retval;
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a 1x1 resultset and takes no parameters) against the provided SQLiteTransaction. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int orderCount = (int)ExecuteScalar(trans, "GetOrderCount");
        /// </remarks>
        /// <param name="transaction">A valid SQLiteTransaction</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
        public static object ExecuteScalar(SQLiteTransaction transaction, string commandText)
        {
            // Pass through the call providing null for the set of SQLiteParameters
            return ExecuteScalar(transaction, commandText, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a 1x1 resultset) against the specified SQLiteTransaction
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int orderCount = (int)ExecuteScalar(trans, "GetOrderCount", new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="transaction">A valid SQLiteTransaction</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
        public static object ExecuteScalar(SQLiteTransaction transaction, string commandText,
                                           params SQLiteParameter[] commandParameters)
        {
            if (transaction == null) throw new ArgumentNullException("transaction");
            if (transaction != null && transaction.Connection == null)
                throw new ArgumentException(
                    "The transaction was rollbacked or commited, please provide an open transaction.", "transaction");

            // Create a command and prepare it for execution
            SQLiteCommand cmd = new SQLiteCommand();
            bool mustCloseConnection = false;
            PrepareCommand(cmd, transaction.Connection, transaction, commandText, commandParameters,
                           out mustCloseConnection);

            // Execute the command & return the results
            object retval = cmd.ExecuteScalar();

            // Detach the SQLiteParameters from the command object, so they can be used again
            cmd.Parameters.Clear();
            return retval;
        }

        #endregion ExecuteScalar

        #region FillDataset

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset and takes no parameters) against the database specified in 
        /// the connection string. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  FillDataset("GetOrders", ds, new string[] {"orders"});
        /// </remarks>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
        /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
        /// by a user defined name (probably the actual table name)</param>
        public static void FillDataset(string commandText, DataSet dataSet, string[] tableNames)
        {
            if (dataSet == null) throw new ArgumentNullException("dataSet");

            // Create & open a SQLiteConnection, and dispose of it after we are done
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                connection.Open();

                // Call the overload that takes a connection in place of the connection string
                FillDataset(connection, commandText, dataSet, tableNames);
            }
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  FillDataset("GetOrders", ds, new string[] {"orders"}, new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
        /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
        /// by a user defined name (probably the actual table name)
        /// </param>
        public static void FillDataset(string commandText, DataSet dataSet, string[] tableNames, params SQLiteParameter[] commandParameters)
        {
            if (dataSet == null) throw new ArgumentNullException("dataSet");
            // Create & open a SQLiteConnection, and dispose of it after we are done
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                connection.Open();

                // Call the overload that takes a connection in place of the connection string
                FillDataset(connection, commandText, dataSet, tableNames, commandParameters);
            }
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset and takes no parameters) against the database specified in 
        /// the connection string. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  FillDataset(connString, "GetOrders", ds, new string[] {"orders"});
        /// </remarks>
        /// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
        /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
        /// by a user defined name (probably the actual table name)</param>
        public static void FillDataset(string connectionString, string commandText, DataSet dataSet, string[] tableNames)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString");
            if (dataSet == null) throw new ArgumentNullException("dataSet");

            // Create & open a SQLiteConnection, and dispose of it after we are done
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                // Call the overload that takes a connection in place of the connection string
                FillDataset(connection, commandText, dataSet, tableNames);
            }
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  FillDataset(connString, "GetOrders", ds, new string[] {"orders"}, new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
        /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
        /// by a user defined name (probably the actual table name)
        /// </param>
        public static void FillDataset(string connectionString, string commandText, DataSet dataSet, string[] tableNames, params SQLiteParameter[] commandParameters)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString");
            if (dataSet == null) throw new ArgumentNullException("dataSet");
            // Create & open a SQLiteConnection, and dispose of it after we are done
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                // Call the overload that takes a connection in place of the connection string
                FillDataset(connection, commandText, dataSet, tableNames, commandParameters);
            }
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset and takes no parameters) against the provided SQLiteConnection. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  FillDataset(conn, "GetOrders", ds, new string[] {"orders"});
        /// </remarks>
        /// <param name="connection">A valid SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
        /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
        /// by a user defined name (probably the actual table name)
        /// </param>    
        public static void FillDataset(SQLiteConnection connection, string commandText, DataSet dataSet, string[] tableNames)
        {
            FillDataset(connection, commandText, dataSet, tableNames, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset) against the specified SQLiteConnection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  FillDataset(conn, "GetOrders", ds, new string[] {"orders"}, new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">A valid SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
        /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
        /// by a user defined name (probably the actual table name)
        /// </param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        public static void FillDataset(SQLiteConnection connection, string commandText, DataSet dataSet, string[] tableNames, params SQLiteParameter[] commandParameters)
        {
            FillDataset(connection, null, commandText, dataSet, tableNames, commandParameters);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset and takes no parameters) against the provided SQLiteTransaction. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  FillDataset(trans, "GetOrders", ds, new string[] {"orders"});
        /// </remarks>
        /// <param name="transaction">A valid SQLiteTransaction</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
        /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
        /// by a user defined name (probably the actual table name)
        /// </param>
        public static void FillDataset(SQLiteTransaction transaction, string commandText, DataSet dataSet, string[] tableNames)
        {
            FillDataset(transaction, commandText, dataSet, tableNames, null);
        }

        /// <summary>
        /// Execute a SQLiteCommand (that returns a resultset) against the specified SQLiteTransaction
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  FillDataset(trans, "GetOrders", ds, new string[] {"orders"}, new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="transaction">A valid SQLiteTransaction</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
        /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
        /// by a user defined name (probably the actual table name)
        /// </param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        public static void FillDataset(SQLiteTransaction transaction, string commandText, DataSet dataSet, string[] tableNames,
                                       params SQLiteParameter[] commandParameters)
        {
            FillDataset(transaction.Connection, transaction, commandText, dataSet, tableNames,
                        commandParameters);
        }

        /// <summary>
        /// Private helper method that execute a SQLiteCommand (that returns a resultset) against the specified SQLiteTransaction and SQLiteConnection
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  FillDataset(conn, trans, "GetOrders", ds, new string[] {"orders"}, new SQLiteParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">A valid SQLiteConnection</param>
        /// <param name="transaction">A valid SQLiteTransaction</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
        /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
        /// by a user defined name (probably the actual table name)
        /// </param>
        /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
        private static void FillDataset(SQLiteConnection connection, SQLiteTransaction transaction, string commandText, DataSet dataSet, string[] tableNames, params SQLiteParameter[] commandParameters)
        {
            if (connection == null) throw new ArgumentNullException("connection");
            if (dataSet == null) throw new ArgumentNullException("dataSet");

            // Create a command and prepare it for execution
            SQLiteCommand command = new SQLiteCommand();
            bool mustCloseConnection = false;
            PrepareCommand(command, connection, transaction, commandText, commandParameters,
                           out mustCloseConnection);

            // Create the DataAdapter & DataSet
            using (SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(command))
            {
                // Add the table mappings specified by the user
                if (tableNames != null && tableNames.Length > 0)
                {
                    string tableName = "Table";
                    for (int index = 0; index < tableNames.Length; index++)
                    {
                        if (string.IsNullOrEmpty(tableNames[index]))
                            throw new ArgumentException(
                                "The tableNames parameter must contain a list of tables, a value was provided as null or empty string.",
                                "tableNames");
                        dataAdapter.TableMappings.Add(tableName, tableNames[index]);
                        tableName += (index + 1).ToString();
                    }
                }

                // Fill the DataSet using default values for DataTable names, etc
                dataAdapter.Fill(dataSet);

                // Detach the SQLiteParameters from the command object, so they can be used again
                command.Parameters.Clear();
            }

            if (mustCloseConnection)
                connection.Close();
        }

        #endregion

        #region UpdateDataset

        /// <summary>
        /// Executes the respective command for each inserted, updated, or deleted row in the DataSet.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  UpdateDataset(conn, insertCommand, deleteCommand, updateCommand, dataSet, "Order");
        /// </remarks>
        /// <param name="insertCommand">A valid transact-SQL statement or stored procedure to insert new records into the data source</param>
        /// <param name="deleteCommand">A valid transact-SQL statement or stored procedure to delete records from the data source</param>
        /// <param name="updateCommand">A valid transact-SQL statement or stored procedure used to update records in the data source</param>
        /// <param name="dataSet">The DataSet used to update the data source</param>
        /// <param name="tableName">The DataTable used to update the data source.</param>
        public static void UpdateDataset(SQLiteCommand insertCommand, SQLiteCommand deleteCommand, SQLiteCommand updateCommand,
                                         DataSet dataSet, string tableName)
        {
            if (insertCommand == null) throw new ArgumentNullException("insertCommand");
            if (deleteCommand == null) throw new ArgumentNullException("deleteCommand");
            if (updateCommand == null) throw new ArgumentNullException("updateCommand");
            if (string.IsNullOrEmpty(tableName)) throw new ArgumentNullException("tableName");

            // Create a SQLiteDataAdapter, and dispose of it after we are done
            using (SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter())
            {
                // Set the data adapter commands
                dataAdapter.UpdateCommand = updateCommand;
                dataAdapter.InsertCommand = insertCommand;
                dataAdapter.DeleteCommand = deleteCommand;

                // Update the dataset changes in the data source
                dataAdapter.Update(dataSet, tableName);

                // Commit all the changes made to the DataSet
                dataSet.AcceptChanges();
            }
        }

        #endregion

        #region ����Update����

        /// <summary>
        /// ����ָ�����������ֶ�ֵ
        /// </summary>
        /// <param name="tableName">���ݱ�����</param>
        /// <param name="where">WHERE������䣬������WHERE��������ԡ�</param>
        /// <param name="whereParameters">������������</param>
        /// <param name="updateParameters">���²�������</param>
        /// <returns>����Ӱ�������</returns>
        public static int Update(string tableName, string where, SQLiteParameter[] whereParameters, SQLiteParameter[] updateParameters)
        {
            if (updateParameters == null || updateParameters.Length == 0)
            {
                throw new ArgumentOutOfRangeException("���봫����²�����");
            }

            string sql = CreateUpdateSql(tableName, where, whereParameters, updateParameters);

            // ��Ҫ��������������ϲ�Ϊһ��
            SQLiteParameter[] args = MergeParameters(whereParameters, updateParameters);

            return SqliteHelper.ExecuteNonQuery(sql, args);
        }

        /// <summary>
        /// ����ָ�����������ֶ�ֵ
        /// </summary>
        /// <param name="tableName">���ݱ�����</param>
        /// <param name="whereParameters">������������</param>
        /// <param name="updateParameters">���²�������</param>
        /// <returns>����Ӱ�������</returns>
        public static int Update(string tableName, SQLiteParameter[] whereParameters, SQLiteParameter[] updateParameters)
        {
            return Update(tableName, CreateWhereSql(whereParameters), whereParameters, updateParameters);
        }

        /// <summary>
        /// ����ָ�����������ֶ�ֵ
        /// </summary>
        /// <param name="tableName">���ݱ�����</param>
        /// <param name="parameters">�������飬�������������͸��¼��ϲ���������������ǰ�棬���²����ں���</param>
        /// <param name="whereParameterCount">������������������������ò�����Ĭ��Ϊ1</param>
        /// <returns>����Ӱ�������</returns>
        public static int Update(string tableName, SQLiteParameter[] parameters, int whereParameterCount)
        {
            if (whereParameterCount < 0 || whereParameterCount >= parameters.Length)
            {
                throw new ArgumentOutOfRangeException("������������������С���㣬���ܴ��ڲ���������������������Ҫ��һ�����²�����");
            }

            // ��Ҫ�����������������͸��²�������
            SQLiteParameter[] whereParameters = new SQLiteParameter[whereParameterCount];
            SQLiteParameter[] updateParameters = new SQLiteParameter[parameters.Length - whereParameterCount];
            for (int i = 0, j = whereParameterCount; i < j; i++)
            {
                whereParameters[i] = parameters[i];
            }

            for (int i = 0, j = parameters.Length - whereParameterCount; i < j; i++)
            {
                updateParameters[i] = parameters[i + whereParameterCount];
            }

            return Update(tableName, whereParameters, updateParameters);
        }

        /// <summary>
        /// ����ָ�����������ֶ�ֵ��Ĭ����������Ϊ��1����
        /// </summary>
        /// <param name="tableName">���ݱ�����</param>
        /// <param name="parameters">�������飬�������������͸��¼��ϲ���������������ǰ�棬���²����ں���</param>
        /// <returns>����Ӱ�������</returns>
        public static int Update(string tableName, SQLiteParameter[] parameters)
        {
            return Update(tableName, parameters, 1);
        }

        #endregion ����Update����

        #region ����SQL���ȷ���

        /// <summary>
        /// ����UPDATE����ʱ��SQL������ֵ��䣬����SET�ؼ���
        /// </summary>
        /// <param name="updateParameters">���²�������</param>
        /// <returns>UPDATE����SQL���</returns>
        public static string CreateUpdateParameterSql(SQLiteParameter[] updateParameters)
        {
            StringBuilder sb = new StringBuilder();

            if (updateParameters.Length > 0)
            {
                for (int i = 0, j = updateParameters.Length; i < j; i++)
                {
                    SQLiteParameter parameter = updateParameters[i];
                    if (i > 0)
                    {
                        sb.Append(", ");
                    }
                    // ��Ҫȥ������������ǰ���@�ַ�
                    sb.AppendFormat("[{0}] = {1}", parameter.ParameterName.Remove(0, 1), parameter.ParameterName);
                }
            }

            return sb.ToString();
        }

        /// <summary>
        /// ����WHERE����SQL��䣬��WHERE�ؼ��֡������������Ϊ0���򷵻ؿշ�����
        /// </summary>
        /// <param name="whereParameters">������������</param>
        /// <returns>WHERE����SQL��䡣�磺WHERE [ID] = @ID AND [NAME] = @NAME</returns>
        public static string CreateWhereSql(SQLiteParameter[] whereParameters)
        {
            StringBuilder sb = new StringBuilder();

            if (whereParameters.Length > 0)
            {
                sb.Append(" WHERE ");
                for (int i = 0, j = whereParameters.Length; i < j; i++)
                {
                    SQLiteParameter parameter = whereParameters[i];
                    if (i > 0)
                    {
                        sb.Append(" AND ");
                    }
                    // ��Ҫȥ������������ǰ���@�ַ�
                    sb.AppendFormat("[{0}] = {1}", parameter.ParameterName.Remove(0, 1), parameter.ParameterName);
                }
            }

            return sb.ToString();
        }

        /// <summary>
        /// ����UPDATE����SQL��䡣
        /// </summary>
        /// <param name="tableName">���ݱ�����</param>
        /// <param name="where">WHERE������䣬������WHERE��������ԡ�</param>
        /// <param name="whereParameters">������������</param>
        /// <param name="updateParameters">���²�������</param>
        /// <returns>UPDATE����SQL���</returns>
        public static string CreateUpdateSql(string tableName, string where, SQLiteParameter[] whereParameters, SQLiteParameter[] updateParameters)
        {
            if (where.Trim().Length > 0 && !where.Trim().StartsWith("WHERE", StringComparison.OrdinalIgnoreCase))
            {
                where = "WHERE " + where;
            }

            string sql = string.Format(@"
UPDATE [{0}]
SET {1}
{2}
", tableName, CreateUpdateParameterSql(updateParameters), where);

            return sql;
        }

        /// <summary>
        /// ����EXISTS��ѯSQL���
        /// </summary>
        /// <param name="tableName">���ݱ�����</param>
        /// <param name="where">WHERE������䣬������WHERE��������ԡ�</param>
        /// <param name="whereParameters">������������</param>
        /// <returns>EXISTS��ѯSQL���</returns>
        public static string CreateExistSql(string tableName, string where, SQLiteParameter[] whereParameters)
        {
            if (where.Trim().Length > 0 && !where.Trim().StartsWith("WHERE", StringComparison.OrdinalIgnoreCase))
            {
                where = "WHERE " + where;
            }

            string sql = string.Format(@"
IF EXISTS
(
    SELECT *
    FROM [{0}]
    {1}
)
BEGIN
    SELECT 1
END
", tableName, where);

            return sql;
        }

        /// <summary>
        /// ����DELETEɾ��SQL���
        /// </summary>
        /// <param name="tableName">���ݱ�����</param>
        /// <param name="where">WHERE������䣬������WHERE��������ԡ�</param>
        /// <param name="whereParameters">������������</param>
        /// <returns>DELETEɾ��SQL���</returns>
        public static string CreateDeleteSql(string tableName, string where, SQLiteParameter[] whereParameters)
        {
            if (where.Trim().Length > 0 && !where.Trim().StartsWith("WHERE", StringComparison.OrdinalIgnoreCase))
            {
                where = "WHERE " + where;
            }
            string sql = string.Format("DELETE [{0}] {1}", tableName, where);

            return sql;
        }

        /// <summary>
        /// ����SELECT COUNT��ѯSQL���
        /// </summary>
        /// <param name="tableName">���ݱ�����</param>
        /// <param name="where">WHERE������䣬������WHERE��������ԡ�</param>
        /// <param name="whereParameters">������������</param>
        /// <returns>SELECT COUNT��ѯSQL���</returns>
        public static string CreateSelectCountSql(string tableName, string where, SQLiteParameter[] whereParameters)
        {
            if (where.Trim().Length > 0 && !where.Trim().StartsWith("WHERE", StringComparison.OrdinalIgnoreCase))
            {
                where = "WHERE " + where;
            }

            string sql = string.Format(@"
SELECT COUNT(*)
FROM [{0}]
{1}
", tableName, where);

            return sql;
        }

        /// <summary>
        /// ����SELECT��ѯSQL��䡣
        /// </summary>
        /// <param name="tableName">���ݱ����ͼ���ƣ�����ѯʱ���ݱ�������Ҫ����JOIN ON����</param>
        /// <param name="getFields">Ҫ��ȡ���ֶ����ƣ�����Ϊ*��</param>
        /// <param name="orderBy">ORDER BY�����ֶΣ�������ORDER BY��������ԡ�</param>
        /// <param name="where">WHERE������䣬������WHERE��������ԡ�</param>
        /// <param name="whereParameters">������������</param>
        /// <returns>SELECT COUNT��ѯSQL���</returns>
        public static string CreateSelectSql(string tableName, string getFields, string orderBy, string where)
        {
            if (getFields == "")
            {
                getFields = "*";
            }

            if (where.Trim().Length > 0 && !where.Trim().StartsWith("WHERE", StringComparison.OrdinalIgnoreCase))
            {
                where = "WHERE " + where;
            }
            if (where.Trim().Length > 0 && !where.Trim().StartsWith("ORDER BY", StringComparison.OrdinalIgnoreCase))
            {
                where = "ORDER BY " + where;
            }

            string sql = string.Format(@"
SELECT {0}
FROM [{1}]
{2}
{3}
", getFields, tableName, where, orderBy);

            return sql;
        }

        /// <summary>
        /// �ϲ��������顣
        /// </summary>
        /// <param name="parameters1">��������1</param>
        /// <param name="parameters2">��������2</param>
        /// <returns>�ϲ���Ĳ�������</returns>
        public static SQLiteParameter[] MergeParameters(SQLiteParameter[] parameters1, SQLiteParameter[] parameters2)
        {
            int length1 = parameters1.Length;
            int length2 = parameters2.Length;
            SQLiteParameter[] args = new SQLiteParameter[length1 + length2];
            for (int i = 0; i < length1; i++)
            {
                args[i] = parameters1[i];
            }
            for (int i = 0; i < length2; i++)
            {
                args[i + length1] = parameters2[i];
            }

            return args;
        }

        /// <summary>
        /// ��¡Sql�������飬�Դﵽ���õ�Ŀ��
        /// Sql��������Ϊ���÷�ʽ�������ظ�ʹ��
        /// </summary>
        /// <param name="originalParameters">ԭʼSql��������</param>
        /// <returns>Sql��������</returns>
        public static SQLiteParameter[] CloneParameters(SQLiteParameter[] originalParameters)
        {
            SQLiteParameter[] clonedParameters = new SQLiteParameter[originalParameters.Length];

            for (int i = 0, j = originalParameters.Length; i < j; i++)
            {
                clonedParameters[i] = (SQLiteParameter)((ICloneable)originalParameters[i]).Clone();
            }

            return clonedParameters;
        }

        #endregion ����SQL���ȷ���

        #region ���ɷ�ҳ

        /// <summary>
        /// ���ɷ�ҳSQL���
        /// </summary>
        /// <param name="startRowIndex">Ҫ�����ĵ�һ������ֵ</param>
        /// <param name="maximumRows">Ҫ������ÿҳ�������</param>
        /// <param name="table">��������ͼ���ơ�����Ƕ�������ѯ����Ҫ�ȶ������ͼ��Ȼ���ٶ���ͼ��ҳ��</param>
        /// <param name="getFields">Ҫ��ȡ���ֶΣ�ȫ��Ϊ"*"��</param>
        /// <param name="keyField">�����ֶ�</param>
        /// <param name="orderByAsc">�Ƿ�Ϊ����</param>
        /// <param name="where">������䣬����Ҫ��WHERE</param>
        /// <returns>��ҳSQL���</returns>
        public static string CreatePagedSql(int startRowIndex, int maximumRows, string table, string getFields, string keyField, bool orderByAsc, string where)
        {
            string sql, temp, orderBy, tempOrderBy;

            if (where != string.Empty)
            {
                where = String.Format(" WHERE {0}", where);
            }

            if (orderByAsc)
            {
                temp = " > ( SELECT TOP 1";
                orderBy = String.Format(" ORDER BY [{0}] ASC", keyField);
                tempOrderBy = String.Format(" ORDER BY [{0}] DESC", keyField);
            }
            else
            {
                temp = " < ( SELECT TOP 1";
                orderBy = String.Format(" ORDER BY [{0}] DESC", keyField);
                tempOrderBy = String.Format(" ORDER BY [{0}] ASC", keyField);
            }

            if (startRowIndex == 0)
            {
                // ����ǵ�һҳ��ִ�����´��룬������ӿ�ִ���ٶ�
                sql = String.Format("SELECT TOP {0} {1} FROM [{2}] {3} {4}", maximumRows, getFields, table, where, orderBy);
            }
            else
            {
                sql = String.Format("SELECT TOP {0} {1} FROM [{2}] WHERE [{3}] {4} [{3}] FROM (SELECT TOP {5} [{3}] FROM [{2}] {6} {7}) AS TempTable {8}) {9} {7}", maximumRows, getFields, table, keyField, temp, startRowIndex, where, orderBy, tempOrderBy, where.Replace("WHERE", "AND"));
            }

            return sql;
        }

        /// <summary>
        /// ���ɻ�ȡ��¼���������
        /// </summary>
        /// <param name="table">��������ͼ���ơ�����Ƕ�������ѯ����Ҫ�ȶ������ͼ��Ȼ���ٶ���ͼ��ҳ��</param>
        /// <param name="where">������䣬����Ҫ��WHERE</param>
        /// <returns>SQL���</returns>
        public static string CreateRecordCountSql(string table, string where)
        {
            if (where != string.Empty)
            {
                where = String.Format(" WHERE ({0})", where);
            }

            string sql = String.Format("SELECT COUNT(*) FROM [{0}] {1}", table, where);

            return sql;
        }

        /// <summary>
        /// ��ȡ��ҳ��¼��ʹ����Ϻ�һ��Ҫ��ʱ�ر�SqlDataReader��
        /// </summary>
        /// <param name="recordCount">������ϲ�ѯ�����ļ�¼������</param>
        /// <param name="startRowIndex">Ҫ�����ĵ�һ������ֵ</param>
        /// <param name="maximumRows">Ҫ������ÿҳ�������</param>
        /// <param name="table">��������ͼ���ơ�����Ƕ�������ѯ����Ҫ�ȶ������ͼ��Ȼ���ٶ���ͼ��ҳ��</param>
        /// <param name="getFields">Ҫ��ȡ���ֶΣ�ȫ��Ϊ"*"��</param>
        /// <param name="keyField">�����ֶ�</param>
        /// <param name="orderByAsc">�Ƿ�Ϊ����</param>
        /// <param name="where">������䣬����Ҫ��WHERE</param>
        /// <param name="args">��������</param>
        /// <returns>������¼��SqlDataReader</returns>
        public static SQLiteDataReader ExecutePagedReader(out int recordCount, int startRowIndex, int maximumRows, string table, string getFields, string keyField, bool orderByAsc, string where, SQLiteParameter[] args)
        {
            recordCount = SelectCount(table, where, args);

            // �������鲻����ֱ�Ӹ��ã���¡��������
            args = SqliteHelper.CloneParameters(args);

            string sql = CreatePagedSql(startRowIndex, maximumRows, table, getFields, keyField, orderByAsc, where);

            return ExecuteReader(sql, args);
        }

        /// <summary>
        /// ��ȡ��ҳ��¼��ʹ����Ϻ�һ��Ҫ��ʱ�ر�SqlDataReader
        /// </summary>
        /// <param name="recordCount">������ϲ�ѯ�����ļ�¼������</param>
        /// <param name="startRowIndex">Ҫ�����ĵ�һ������ֵ</param>
        /// <param name="maximumRows">Ҫ������ÿҳ�������</param>
        /// <param name="table">��������ͼ���ơ�����Ƕ�������ѯ����Ҫ�ȶ������ͼ��Ȼ���ٶ���ͼ��ҳ��</param>
        /// <param name="getFields">Ҫ��ȡ���ֶΣ�ȫ��Ϊ"*"��</param>
        /// <param name="keyField">�����ֶ�</param>
        /// <param name="orderByAsc">�Ƿ�Ϊ����</param>
        /// <returns>������¼��SqlDataReader</returns>
        public static SQLiteDataReader ExecutePagedReader(out int recordCount, int startRowIndex, int maximumRows, string table, string getFields, string keyField, bool orderByAsc)
        {
            return ExecutePagedReader(out recordCount, startRowIndex, maximumRows, table, getFields, keyField, orderByAsc, string.Empty, (SQLiteParameter[])null);
        }

        /// <summary>
        /// ��ȡ��ҳ��¼
        /// </summary>
        /// <param name="recordCount">������ϲ�ѯ�����ļ�¼������</param>
        /// <param name="startRowIndex">Ҫ�����ĵ�һ������ֵ</param>
        /// <param name="maximumRows">Ҫ������ÿҳ�������</param>
        /// <param name="table">��������ͼ���ơ�����Ƕ�������ѯ����Ҫ�ȶ������ͼ��Ȼ���ٶ���ͼ��ҳ��</param>
        /// <param name="getFields">Ҫ��ȡ���ֶΣ�ȫ��Ϊ"*"��</param>
        /// <param name="keyField">�����ֶ�</param>
        /// <param name="orderByAsc">�Ƿ�Ϊ����</param>
        /// <param name="where">������䣬����Ҫ��WHERE</param>
        /// <param name="args">��������</param>
        /// <returns>������¼��DataSet</returns>
        public static DataSet ExecutePagedDataset(out int recordCount, int startRowIndex, int maximumRows, string table, string getFields, string keyField, bool orderByAsc, string where, SQLiteParameter[] args)
        {
            recordCount = SelectCount(table, where, args);

            // �������鲻����ֱ�Ӹ��ã���¡��������
            args = SqliteHelper.CloneParameters(args);

            string sql = CreatePagedSql(startRowIndex, maximumRows, table, getFields, keyField, orderByAsc, where);

            return ExecuteDataset(sql, args);
        }

        /// <summary>
        /// ��ȡ��ҳ��¼
        /// </summary>
        /// <param name="recordCount">������ϲ�ѯ�����ļ�¼������</param>
        /// <param name="startRowIndex">Ҫ�����ĵ�һ������ֵ</param>
        /// <param name="maximumRows">Ҫ������ÿҳ�������</param>
        /// <param name="table">��������ͼ���ơ�����Ƕ�������ѯ����Ҫ�ȶ������ͼ��Ȼ���ٶ���ͼ��ҳ��</param>
        /// <param name="getFields">Ҫ��ȡ���ֶΣ�ȫ��Ϊ"*"��</param>
        /// <param name="keyField">�����ֶ�</param>
        /// <param name="orderByAsc">�Ƿ�Ϊ����</param>
        /// <returns>������¼��DataSet</returns>
        public static DataSet ExecutePagedDataset(out int recordCount, int startRowIndex, int maximumRows, string table, string getFields, string keyField, bool orderByAsc)
        {
            return ExecutePagedDataset(out recordCount, startRowIndex, maximumRows, table, getFields, keyField, orderByAsc, string.Empty, (SQLiteParameter[])null);
        }

        /// <summary>
        /// ��ȡ��ҳ��¼��ʹ����Ϻ�һ��Ҫ��ʱ�ر�SqlDataReader
        /// </summary>
        /// <param name="startRowIndex">Ҫ�����ĵ�һ������ֵ</param>
        /// <param name="maximumRows">Ҫ������ÿҳ�������</param>
        /// <param name="table">��������ͼ���ơ�����Ƕ�������ѯ����Ҫ�ȶ������ͼ��Ȼ���ٶ���ͼ��ҳ��</param>
        /// <param name="getFields">Ҫ��ȡ���ֶΣ�ȫ��Ϊ"*"��</param>
        /// <param name="keyField">�����ֶ�</param>
        /// <param name="orderByAsc">�Ƿ�Ϊ����</param>
        /// <param name="where">������䣬����Ҫ��WHERE</param>
        /// <param name="args">��������</param>
        /// <returns>������¼��SqlDataReader</returns>
        public static SQLiteDataReader ExecutePagedReader(int startRowIndex, int maximumRows, string table, string getFields, string keyField, bool orderByAsc, string where, SQLiteParameter[] args)
        {
            string sql = CreatePagedSql(startRowIndex, maximumRows, table, getFields, keyField, orderByAsc, where);

            return ExecuteReader(sql, args);
        }

        /// <summary>
        /// ��ȡ��ҳ��¼��ʹ����Ϻ�һ��Ҫ��ʱ�ر�SqlDataReader
        /// </summary>
        /// <param name="startRowIndex">Ҫ�����ĵ�һ������ֵ</param>
        /// <param name="maximumRows">Ҫ������ÿҳ�������</param>
        /// <param name="table">��������ͼ���ơ�����Ƕ�������ѯ����Ҫ�ȶ������ͼ��Ȼ���ٶ���ͼ��ҳ��</param>
        /// <param name="getFields">Ҫ��ȡ���ֶΣ�ȫ��Ϊ"*"��</param>
        /// <param name="keyField">�����ֶ�</param>
        /// <param name="orderByAsc">�Ƿ�Ϊ����</param>
        /// <returns>������¼��SqlDataReader</returns>
        public static SQLiteDataReader ExecutePagedReader(int startRowIndex, int maximumRows, string table, string getFields, string keyField, bool orderByAsc)
        {
            return ExecutePagedReader(startRowIndex, maximumRows, table, getFields, keyField, orderByAsc, string.Empty, (SQLiteParameter[])null);
        }

        /// <summary>
        /// ��ȡ��ҳ��¼
        /// </summary>
        /// <param name="startRowIndex">Ҫ�����ĵ�һ������ֵ</param>
        /// <param name="maximumRows">Ҫ������ÿҳ�������</param>
        /// <param name="table">��������ͼ���ơ�����Ƕ�������ѯ����Ҫ�ȶ������ͼ��Ȼ���ٶ���ͼ��ҳ��</param>
        /// <param name="getFields">Ҫ��ȡ���ֶΣ�ȫ��Ϊ"*"��</param>
        /// <param name="keyField">�����ֶ�</param>
        /// <param name="orderByAsc">�Ƿ�Ϊ����</param>
        /// <param name="where">������䣬����Ҫ��WHERE</param>
        /// <param name="args">��������</param>
        /// <returns>������¼��DataSet</returns>
        public static DataSet ExecutePagedDataset(int startRowIndex, int maximumRows, string table, string getFields, string keyField, bool orderByAsc, string where, SQLiteParameter[] args)
        {
            string sql = CreatePagedSql(startRowIndex, maximumRows, table, getFields, keyField, orderByAsc, where);

            return ExecuteDataset(sql, args);
        }

        /// <summary>
        /// ��ȡ��ҳ��¼
        /// </summary>
        /// <param name="startRowIndex">Ҫ�����ĵ�һ������ֵ</param>
        /// <param name="maximumRows">Ҫ������ÿҳ�������</param>
        /// <param name="table">��������ͼ���ơ�����Ƕ�������ѯ����Ҫ�ȶ������ͼ��Ȼ���ٶ���ͼ��ҳ��</param>
        /// <param name="getFields">Ҫ��ȡ���ֶΣ�ȫ��Ϊ"*"��</param>
        /// <param name="keyField">�����ֶ�</param>
        /// <param name="orderByAsc">�Ƿ�Ϊ����</param>
        /// <returns>������¼��DataSet</returns>
        public static DataSet ExecutePagedDataset(int startRowIndex, int maximumRows, string table, string getFields, string keyField, bool orderByAsc)
        {
            return ExecutePagedDataset(startRowIndex, maximumRows, table, getFields, keyField, orderByAsc, string.Empty, (SQLiteParameter[])null);
        }

        /// <summary>
        /// ��ȡ��¼����
        /// </summary>
        /// <param name="table">��������ͼ���ơ�����Ƕ�������ѯ����Ҫ�ȶ������ͼ��Ȼ���ٶ���ͼ��ҳ��</param>
        /// <param name="where">������䣬����Ҫ��WHERE</param>
        /// <param name="args">��������</param>
        /// <returns>��¼����</returns>
        public static int GetRecordCount(string table, string where, SQLiteParameter[] args)
        {
            string sql = CreateRecordCountSql(table, where);
            int recordCount = (int)ExecuteScalar(sql, args);

            return recordCount;
        }

        /// <summary>
        /// ��ȡ��¼����
        /// </summary>
        /// <param name="table">��������ͼ���ơ�����Ƕ�������ѯ����Ҫ�ȶ������ͼ��Ȼ���ٶ���ͼ��ҳ��</param>
        /// <returns>��¼����</returns>
        [Obsolete("�÷����ѹ�ʱ����ʹ��SelectCount�������档")]
        public static int GetRecordCount(string table)
        {
            return GetRecordCount(table, string.Empty, (SQLiteParameter[])null);
        }

        #endregion ���ɷ�ҳ

        #region ����SelectCount����

        /// <summary>
        /// ��ѯ����ָ�������ļ�¼����
        /// </summary>
        /// <param name="tableName">���ݱ�����</param>
        /// <param name="where">WHERE������䣬������WHERE��������ԡ�</param>
        /// <param name="whereParameters">������������</param>
        /// <returns>����ָ�������ļ�¼����</returns>
        public static int SelectCount(string tableName, string where, SQLiteParameter[] whereParameters)
        {
            string sql = CreateSelectCountSql(tableName, where, whereParameters);

            return (int)SqliteHelper.ExecuteScalar(sql, whereParameters);
        }

        /// <summary>
        /// ��ѯ����ָ�������ļ�¼����
        /// </summary>
        /// <param name="tableName">���ݱ�����</param>
        /// <param name="whereParameters">������������</param>
        /// <returns>����ָ�������ļ�¼����</returns>
        public static int SelectCount(string tableName, SQLiteParameter[] whereParameters)
        {
            return SelectCount(tableName, CreateWhereSql(whereParameters), whereParameters);
        }

        /// <summary>
        /// ��ѯ����ָ�������ļ�¼����
        /// </summary>
        /// <param name="tableName">���ݱ�����</param>
        /// <param name="whereParameter">��������</param>
        /// <returns>����ָ�������ļ�¼����</returns>
        public static int SelectCount(string tableName, SQLiteParameter whereParameter)
        {
            SQLiteParameter[] whereParameters = new SQLiteParameter[1];
            whereParameters[0] = whereParameter;

            return SelectCount(tableName, whereParameters);
        }

        /// <summary>
        /// ��ѯ����ָ�������ļ�¼����
        /// </summary>
        /// <param name="tableName">���ݱ�����</param>
        /// <returns>����ָ�������ļ�¼����</returns>
        public static int SelectCount(string tableName)
        {
            return SelectCount(tableName, new SQLiteParameter[0]);
        }

        #endregion ����SelectCount����
    }

    /// <summary>
    /// SQLiteHelperParameterCache provides functions to leverage a static cache of procedure parameters, and the
    /// ability to discover parameters for stored procedures at run-time.
    /// </summary>
    public sealed class SQLiteHelperParameterCache
    {
        #region private methods, variables, and constructors

        //Since this class provides only static methods, make the default constructor private to prevent 
        //instances from being created with "new SQLiteHelperParameterCache()"
        private SQLiteHelperParameterCache()
        {
        }

        private static readonly Hashtable paramCache = Hashtable.Synchronized(new Hashtable());

        /// <summary>
        /// Deep copy of cached SQLiteParameter array
        /// </summary>
        /// <param name="originalParameters"></param>
        /// <returns></returns>
        private static SQLiteParameter[] CloneParameters(SQLiteParameter[] originalParameters)
        {
            SQLiteParameter[] clonedParameters = new SQLiteParameter[originalParameters.Length];

            for (int i = 0, j = originalParameters.Length; i < j; i++)
            {
                clonedParameters[i] = (SQLiteParameter)originalParameters[i].Clone();
            }

            return clonedParameters;
        }

        #endregion private methods, variables, and constructors

        #region caching functions

        /// <summary>
        /// Add parameter array to the cache
        /// </summary>
        /// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">An array of SqlParamters to be cached</param>
        public static void CacheParameterSet(string connectionString, string commandText,
                                             params SQLiteParameter[] commandParameters)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString");
            if (string.IsNullOrEmpty(commandText)) throw new ArgumentNullException("commandText");

            string hashKey = connectionString + ":" + commandText;

            paramCache[hashKey] = commandParameters;
        }

        /// <summary>
        /// Retrieve a parameter array from the cache
        /// </summary>
        /// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        /// <param name="commandText">The stored procedure name or T-SQL command</param>
        /// <returns>An array of SqlParamters</returns>
        public static SQLiteParameter[] GetCachedParameterSet(string connectionString, string commandText)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString");
            if (string.IsNullOrEmpty(commandText)) throw new ArgumentNullException("commandText");

            string hashKey = connectionString + ":" + commandText;

            SQLiteParameter[] cachedParameters = paramCache[hashKey] as SQLiteParameter[];
            if (cachedParameters == null)
            {
                return null;
            }

            return CloneParameters(cachedParameters);
        }

        #endregion caching functions

        #region Parameter Discovery Functions

        ///// <summary>
        ///// Retrieves the set of SQLiteParameters appropriate for the stored procedure
        ///// </summary>
        ///// <remarks>
        ///// This method will query the database for this information, and then store it in a cache for future requests.
        ///// </remarks>
        ///// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        ///// <param name="commandText">The name of the stored procedure</param>
        ///// <returns>An array of SQLiteParameters</returns>
        //public static SQLiteParameter[] GetSpParameterSet(string connectionString, string commandText)
        //{
        //    return GetSpParameterSet(connectionString, commandText, false);
        //}

        ///// <summary>
        ///// Retrieves the set of SQLiteParameters appropriate for the stored procedure
        ///// </summary>
        ///// <remarks>
        ///// This method will query the database for this information, and then store it in a cache for future requests.
        ///// </remarks>
        ///// <param name="connectionString">A valid connection string for a SQLiteConnection</param>
        ///// <param name="commandText">The name of the stored procedure</param>
        ///// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
        ///// <returns>An array of SQLiteParameters</returns>
        //public static SQLiteParameter[] GetSpParameterSet(string connectionString, string commandText,
        //                                               bool includeReturnValueParameter)
        //{
        //    if (string.IsNullOrEmpty(connectionString))
        //        throw new ArgumentNullException("connectionString");
        //    if (string.IsNullOrEmpty(commandText)) throw new ArgumentNullException("commandText");

        //    using (SQLiteConnection connection = new SQLiteConnection(connectionString))
        //    {
        //        return GetSpParameterSetInternal(connection, commandText, includeReturnValueParameter);
        //    }
        //}

        ///// <summary>
        ///// Retrieves the set of SQLiteParameters appropriate for the stored procedure
        ///// </summary>
        ///// <remarks>
        ///// This method will query the database for this information, and then store it in a cache for future requests.
        ///// </remarks>
        ///// <param name="connection">A valid SQLiteConnection object</param>
        ///// <param name="commandText">The name of the stored procedure</param>
        ///// <returns>An array of SQLiteParameters</returns>
        //internal static SQLiteParameter[] GetSpParameterSet(SQLiteConnection connection, string commandText)
        //{
        //    return GetSpParameterSet(connection, commandText, false);
        //}

        ///// <summary>
        ///// Retrieves the set of SQLiteParameters appropriate for the stored procedure
        ///// </summary>
        ///// <remarks>
        ///// This method will query the database for this information, and then store it in a cache for future requests.
        ///// </remarks>
        ///// <param name="connection">A valid SQLiteConnection object</param>
        ///// <param name="commandText">The name of the stored procedure</param>
        ///// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
        ///// <returns>An array of SQLiteParameters</returns>
        //internal static SQLiteParameter[] GetSpParameterSet(SQLiteConnection connection, string commandText,
        //                                                 bool includeReturnValueParameter)
        //{
        //    if (connection == null) throw new ArgumentNullException("connection");
        //    using (SQLiteConnection clonedConnection = (SQLiteConnection) ((ICloneable) connection).Clone())
        //    {
        //        return GetSpParameterSetInternal(clonedConnection, commandText, includeReturnValueParameter);
        //    }
        //}

        ///// <summary>
        ///// Retrieves the set of SQLiteParameters appropriate for the stored procedure
        ///// </summary>
        ///// <param name="connection">A valid SQLiteConnection object</param>
        ///// <param name="commandText">The name of the stored procedure</param>
        ///// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
        ///// <returns>An array of SQLiteParameters</returns>
        //private static SQLiteParameter[] GetSpParameterSetInternal(SQLiteConnection connection, string commandText,
        //                                                        bool includeReturnValueParameter)
        //{
        //    if (connection == null) throw new ArgumentNullException("connection");
        //    if (string.IsNullOrEmpty(commandText)) throw new ArgumentNullException("commandText");

        //    string hashKey = connection.ConnectionString + ":" + commandText +
        //                     (includeReturnValueParameter ? ":include ReturnValue Parameter" : "");

        //    SQLiteParameter[] cachedParameters = paramCache[hashKey] as SQLiteParameter[];
        //    if (cachedParameters == null)
        //    {
        //        SQLiteParameter[] spParameters = DiscoverSpParameterSet(connection, commandText, includeReturnValueParameter);
        //        paramCache[hashKey] = spParameters;
        //        cachedParameters = spParameters;
        //    }

        //    return CloneParameters(cachedParameters);
        //}

        #endregion Parameter Discovery Functions
    }
}